<?php
namespace App\Models;

use Maatwebsite\Excel\Facades\Excel;
use Image;

class ReferCode extends BaseModel
{
    protected $table = 'refer_code';
    protected $length = 6;
    protected $create_max = 20; // 一次最多生成数量
    protected $total_max = 100; // 累计总数量

    protected $rules = [
        'code' => 'required|alpha_num|unique:private_code,code|size:6'
    ];

    protected $message = [
        'code.required' => '请输入渠道码',
        'code.alpha_num' => '渠道码只能为字母或数字',
        'code.unique' => '渠道码重复',
        'code.size' => '渠道码长度应为6'
    ];

    /**
     * 生成随机码
     * @param array $already
     * @return bool|string
     */
    protected function getCode(array $already)
    {
        $rangArea = '0123456789abcdefghijklmnopqrstuvwxyz';
        $str = substr(str_shuffle($rangArea),0, $this->length);
        if(in_array($str, $already)) {
            return $this->getCode($already);
        } else {
            return $str;
        }
    }

    public function getReferCodeList($where, $order = [],$pageSize = 20, $pageLength = 10)
    {
        $list = $this->_getPageList($where,'id,code,shop_id,mid,status,code_status',$order,$pageSize,$pageLength);
        if($list) {
            $shopIds = array_unique(array_filter(array_column($list['data'], 'shop_id')));
            $mids = array_unique(array_filter(array_column($list['data'], 'mid')));

            $shopWhere['id'] = ['in', $shopIds];
            $memberWhere['id'] = ['in', $mids];
            $shops = (new Shop())->_getList($shopWhere,'id,shop_name');
            $members = (new Member())->_getList($memberWhere,'id,nickname');
            $list['data'] = collect($list['data'])->map(function ($itemL) use($shops, $members) {
                $itemL['shop_name'] = '';
                $itemL['nickname'] = '';
                $itemL['status_text'] = $itemL['status'] == 1 ? '正常' : '失效';
                $shops->map(function ($itemS) use (&$itemL) {
                    if($itemL['shop_id'] == $itemS['id']){
                        $itemL['shop_name'] = $itemS['shop_name'];
                    }
                });

                $members->map(function ($itemM) use (&$itemL) {
                    if($itemL['mid'] == $itemM['id']){
                        $itemL['nickname'] = $itemM['nickname'];
                    }
                });

                return $itemL;
            })->toArray();
        }
        return $list;
    }

    // 店铺绑定渠道码
    public function bindShopCode()
    {
        $shop_id = request('shop_id');
        $id_start = request('id_start');
        $id_end = request('id_end');
        if(!is_numeric($id_start) || !is_numeric($id_end)) {
            $this->error = '初始序号或结束序号应为数字';
            return false;
        }
        if(!$id_start || !$id_end) {
            $this->error = '请输入初始序号或结束序号';
            return false;
        }
        if($id_start > $id_end) {
            $this->error = '初始序号不得大于结束序号';
            return false;
        }
        $shopInfo = (new Shop())->_getOneById($shop_id);
        if(!$shopInfo) {
            $this->error = '该店铺不存在';
            return false;
        }
        // 判断序号范围内是否有已绑定的数据
        $whereOrigin['id'] = ['between', [$id_start, $id_end]];
        $whereOrigin['code_status'] = 1;
        $unBindCount = $this->_count($whereOrigin,'id');
        unset($whereOrigin['code_status']);
        $originCount = $this->_count($whereOrigin,'id');
        if($unBindCount != $originCount) {
            $this->error = '序号范围内有已绑定的数据';
            return false;
        }

        $updateData = [
            'shop_id' => $shop_id,
            'admin_id' => $shopInfo['admin_id'],
            'code_status' => 2
        ];
        // 只有未绑定店铺的渠道码才能进行绑定操作
        $where['id'] = ['between',[$id_start, $id_end]];
        $where['code_status'] = 1;
        $where['status'] = 1;
        $where['shop_id'] = 0;
        $where['admin_id'] = 0;
        $this->_start();
        try{
            $this->_update($where, $updateData);
            $this->_commit();
        } catch(\Exception $e){
            $this->_rollBack();
            $this->error = '渠道码绑定失败';
            return false;
        }
        return true;
    }

    // 导出功能
    public function exportReferExcel($data)
    {
        return Excel::create('渠道码', function ($excel) use ($data) {
            $excel->sheet('refer_code', function ($sheet) use ($data) {
                $sheet->rows($data);
            });
        })->export('xls');
    }

    // 渠道码绑定用户
    public function bindUserByReferCode($mid, $referCode, $referRatio)
    {
        $result = [
            'status' => 1,
            'msg' => ''
        ];

        $referInfo = $this->_getOne(['code'=>$referCode]);
        // 判断订水码是否绑定过店铺
        if(!$referInfo) {
            $result['status'] = 0;
            $result['msg'] = '该渠道码不存在';
        } else if(!$referInfo['shop_id'] || !$referInfo['admin_id'] || $referInfo['code_status'] == 1) {
            $result['status'] = 0;
            $result['msg'] = '该渠道码未绑定店铺';
        } else if(!$referInfo['status']) {
            $result['status'] = 0;
            $result['msg'] = '该渠道码已失效';
        }

        if(!$result['status']) {
            return $result;
        }

        // 查询当前用户信息
        $memberModel = (new Member());
        $memberInfo = $memberModel->_getOne(['id' => $mid, 'shop_id' => $referInfo['shop_id']]);

        if($referInfo['mid'] && $referInfo['code_status'] == 3) {
            $result['status'] = 0;
            $result['msg'] = '此渠道码已绑定！';
        } else {
            // 渠道码未绑定
            if($memberInfo) {
                // 判断当前用户是否绑定过其他渠道码
                $info = $this->_getOne(['shop_id' => $referInfo['shop_id'], 'mid' => $mid, 'status' => 1]);
                if(!$info) {
                    $this->_start();
                    try{
                        $upMemberData = [
                            'refer_type' => 2,
                            'refer_id' => $referInfo['id'],
                            'refer_ratio' => $referRatio
                        ];
                        $memberModel->_update(['id' => $mid], $upMemberData); // 更新用户信息

                        $upReferData = [
                            'mid' => $mid,
                            'code_status' => 3
                        ];
                        $this->_update(['id' => $referInfo['id']], $upReferData); // 更新渠道码信息

                        // 生成用户佣金信息
                        $commissionModel = new MemberCommission();
                        $commission = $commissionModel->_getOne(['mid' => $mid, 'shop_id' => $referInfo['shop_id']]);
                        if(!$commission) {
                            $commissionData = [
                                'mid' => $mid,
                                'shop_id' => $referInfo['shop_id'],
                                'admin_id' => $referInfo['admin_id'],
                            ];
                            $commissionModel->_save($commissionData);
                        }

                        $this->_commit();
                    }catch(\Exception $e) {
                        $this->_rollBack();
                        $result['status'] = 0;
                        $result['msg'] = '绑定渠道码失败';
                    }
                } else {
                    $result['status'] = 0;
                    $result['msg'] = '该用户绑定已绑定过渠道码';
                }

            } else {
                $result['status'] = 0;
                $result['msg'] = '该用户不存在';
            }
        }

        return $result;
    }

    // 人人分销二维码 base64
    public function personReferQr($tempUrl)
    {
        $format = 'data-url';
        $image = Image::make($tempUrl)->resize(180,180)->response($format)->getContent();
        $baseImage = public_path().'/admin/images/person_refer_default.jpg';
        $mergeImg = Image::make($baseImage)->insert($image,'top-left',150,150)->response($format)->getContent();
        return $mergeImg;
    }

    public function createCodeByMid()
    {
        $mid = request('mid');
        $shop_id = request('shop_id');
        $refer_ratio = request('refer_ratio', 0);

        if($refer_ratio == 0) {
            $this->error = '渠道提成比例不能为0';
            return false;
        }

        $memberModel = new Member();
        $where['id'] = $mid;
        $where['shop_id'] = $shop_id;
        $memberInfo = $memberModel->_getOne($where);
        if(!$memberInfo) {
            $this->error = '操作非法';
            return false;
        }
        $referWhere['mid'] = $mid;
        $referInfo = $this->_getOne($referWhere);
        if($referInfo) {
            $this->error = '此用户已被设置为渠道分销';
            return false;
        }

        // 查询已存在的code
        $list = $this->_getList([],'code');
        $already = array_column($list->toArray(),'code');

        // 查询本店已存在的code数量
        $num = $this->_count(['shop_id' => $shop_id],'id');
        if($num > $this->total_max) {
            $this->error = '一个店铺最多只能设置'.$this->total_max.'个渠道人员';
            return false;
        }

        $this->_start();
        try{
            // 生成渠道码
            $saveData = [
                'code' => $this->getCode($already),
                'shop_id' => $memberInfo['shop_id'],
                'admin_id' => $memberInfo['admin_id'],
                'mid' => $mid,
                'code_status' => 3,
            ];
            $res = $this->_save($saveData);
            if(!$res) {
                $this->_rollBack();
                $this->error = '设置失败';
                return false;
            }

            // 更新用户信息
            $upData = [
                'refer_id' => $res,
                'refer_type' => 2,
                'refer_ratio' => $refer_ratio
            ];
            $memberModel->_update(['id' => $mid], $upData);

            // 生成提成信息
            $commissionData = [
                'mid' => $mid,
                'shop_id' => $memberInfo['shop_id'],
                'admin_id' => $memberInfo['admin_id'],
            ];
            (new MemberCommission())->_save($commissionData);

            $this->_commit();
            return true;
        }catch(\Exception $e) {
            $this->_rollBack();
            $this->error = '系统错误';
            return false;
        }
    }

    // 渠道码合成下载
    public function handleReferQr($img, $baseImg, $code, $alias, $format)
    {
        return response()->stream(function() use ($img, $baseImg, $code, $alias, $format){
            echo Image::make($baseImg)->insert($img,'top-left',172,170)->text($code, 280 ,370, function($font) { // 540,600 x,y坐标
                $font->file(public_path().'/verify/zhttfs/msyh.ttf'); // 字库
                $font->size(20); //文字大小
                $font->color('000000'); // 文字颜色
                $font->align('center'); // 居中对齐
                $font->valign('top'); // 向上垂直对齐
            })->encode($format);
        }, 200, [
            "Content-type"=>"image/png",
            "Content-Disposition"=>"attachment; filename=".$alias.'.'.$format
        ]);
    }
}